package org.cyz.tools.common.util;

import org.cyz.tools.core.assembly.log.Log;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IpUtil {


    private final static String regex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";

    /**
     * 匹配是否符合ip
     * @param ip
     * @return
     */
    public static boolean isIP(String ip){
        Matcher matcher=Pattern.compile(regex).matcher(ip);
        if(matcher.matches()){
            return true;
        }
        return false;
    }

    /**
     * 检测Ip和端口是否可用
     *
     * @param ip
     * @param port
     * @return
     */
    public static boolean checkIpPort(String ip, int port) {
        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress(ip,port),1000);
            Log.info(IpUtil.class.getSimpleName(),"地址和端口号可用");
            return true;
        } catch (Exception e) {
            Log.error(IpUtil.class.getSimpleName(),"地址和端口号不可用");
            return false;
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {

                }
            }
        }

    }
    /**
     * 检测Ip地址
     *
     * @param ip
     * @return
     */
    public static boolean checkIp(String ip){
        try {
            InetAddress.getByName(ip).isReachable(3000);
            Log.info(IpUtil.class.getSimpleName(),"Ip可以使用");
            return true;
        } catch (IOException e) {
            Log.info(IpUtil.class.getSimpleName(),"Ip不可用");
            return false;
        }
    }

}
